package com.na.proxy;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TaskExecutor {

	private List<Task> tasks;
	private Lock lock;
	
	public TaskExecutor() {
		lock = new ReentrantLock();
		tasks = new ArrayList<Task>();
	}
	
	public void runTask(Task task) {
		try {
			lock.lock();
			tasks.add(task);
			new Thread(task).start();
		} finally {
			lock.unlock();
		}
	}
	
	public void stopTask(Task task) {
		try {
			lock.lock();
			task.shutdown();
			tasks.remove(task);
		} finally {
			lock.unlock();
		}
	}

	public void shutdown() {
		try {
			lock.lock();
			for (Task task : tasks) {
				task.shutdown();
			}
			tasks.clear();
		} finally {
			lock.unlock();
		}
	}
	
}
